<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">&emsp;新增&emsp;</el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>

        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table ref="dataList" :data="tableData" :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                  border row-key="id"
                  style="width:100%;margin-bottom: 20px;"
                  @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="ID" prop="id"></el-table-column>
          <el-table-column label="装扮类别" prop="cate_name"></el-table-column>
          <el-table-column label="装扮名称" prop="product_name"></el-table-column>
          <el-table-column label="装扮展示图" prop="picture">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img :src="scope.row.picture" alt="" style="max-width: 200px;max-height: 200px">
                <img slot="reference" :src="scope.row.picture" alt="" style="width: 50px;">
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="动态效果图" prop="special">
            <template slot-scope="{ row }">
              <el-popover
                v-if="/\.(png|jpg|gif|jpeg|webp)$/.test(row.special)"
                max-width="420"
                placement="top"
                trigger="hover"
              >
                <img
                  :src="row.special"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="row.special"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
              <el-popover
                v-else-if="/\.mp4$/.test(row.special)"
                max-width="420"
                placement="top"
                trigger="hover"
              >
                <video
                  :src="row.special"
                  controls
                  style="max-width: 200px; max-height: 200px"
                />
                <video
                  slot="reference"
                  :src="row.special"
                  autoplay
                  style="width: 50px"
                />
              </el-popover>
              <p v-else>{{ row.special }}</p>
            </template>
          </el-table-column>
          <el-table-column label="最小财富值" prop="min_wealth"></el-table-column>
          <el-table-column label="最大财富值" prop="max_wealth"></el-table-column>
          <el-table-column label="添加时间" prop="add_time"></el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button icon="el-icon-edit" plain size="mini" type="primary" @click="handleUpdate(scope.row)">编辑
              </el-button>
              <el-button icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.page_size"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="40%"
    >
      <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
      <span slot="footer" class="dialog-footer">
            <el-button @click="deleteDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmDelete">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="40%"
      @close="handleDialogClose('editRulesForm')"
    >
      <el-form ref="editRulesForm" :model="editRulesForm" :rules="editRulesFormRules" class="demo-ruleForm"
               label-width="120px"
      >
        <el-form-item label="选择类别" prop="cate_id">
          <el-select v-model="editRulesForm.cate_id" placeholder="请选择类别" @change="handleChangeCate">
            <el-option
              v-for="item in categoryOption"
              :key="'类别' + item.id"
              :label="item.title"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="装扮名称" prop="product_name">
          <el-input v-model="editRulesForm.product_name" placeholder="请输入等级名称"></el-input>
        </el-form-item>

        <el-form-item label="装扮展示图" prop="picture">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传装扮展示图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="editRulesForm.cate_id === 4" label="效果" prop="special">
          <div class="flex">
            <el-input v-model="editRulesForm.special" placeholder="请输入色值"></el-input>
          </div>
        </el-form-item>
        <el-form-item v-else label="效果" prop="special">
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="beforeAvatarUpload"
            :file-list="specialFlagBigList2"
            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove2"
            :on-success="handleSpecialFlagBigSuccess2"
            action=""
            class="upload-demo"
            list-type="picture"
          >
            <el-button slot="trigger" size="small" type="primary">上传效果图</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="editRulesForm.cate_id === 2" label="展示位置" prop="show_type">
          <el-radio-group v-model="editRulesForm.show_type">
            <el-radio :label="1">半屏</el-radio>
            <el-radio :label="2">全屏</el-radio>
            <el-radio :label="3">右侧</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="editRulesForm.cate_id === 2"
          label="特效时间"
          prop="time"
        >
          <el-input v-model="editRulesForm.time" class="mr-3" style="width:200px"/>
        </el-form-item>

        <el-form-item v-if="editRulesForm.cate_id === 4" label="展示位置" prop="show_type">
          <el-radio-group v-model="editRulesForm.show_type">
            <el-radio :label="1">旧版</el-radio>
            <el-radio :label="2">新版</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最小财富值" prop="min_wealth">
          <el-input v-model="editRulesForm.min_wealth" placeholder="请输入最小财富值"></el-input>
        </el-form-item>
        <el-form-item label="最大财富值" prop="max_wealth">
          <el-input v-model="editRulesForm.max_wealth" placeholder="请输入最大财富值"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, getCateData, getData, productAdd, productEdit } from '@/api/personalizedMall/commodity'

export default {
  name: 'wealthDress',
  data() {
    return {
      confirmBtn: false,
      specialFlagBigList: [],
      specialFlagBigList2: [],
      categoryOption: [],
      // 要修改的当前行的id
      row_id: 0,
      provinceList: [],
      cityList: [],
      // 表单规则
      editRulesFormRules: {
        time: [{ required: true, message: '请输入', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择装扮类别', trigger: 'blur' }],
        show_type: [{ required: true, message: '请选择展示位置', trigger: 'blur' }],
        product_name: [{ required: true, message: '请输入装扮名称', trigger: 'blur' }],
        min_wealth: [{ required: true, message: '请输入最小财富值', trigger: 'blur' }],
        max_wealth: [{ required: true, message: '请输入最打大财富值', trigger: 'blur' }],
        picture: [{ required: true, message: '请上传装扮展示图', trigger: 'blur' }]
      },
      editRulesForm: {
        id: undefined,
        cate_id: undefined,
        show_type: undefined,
        picture: undefined,
        max_wealth: undefined,
        min_wealth: undefined,
        product_name: undefined,
        style_ids: '1',
        time: undefined
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      tableData: [],
      limitList: [],
      listQuery: {
        cate_id: 0,
        style_id: 0,
        type: 1,
        page: 1,
        page_size: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      // 公屏回声 聊天回声
      extraForm: {
        leftTopImage: '',
        rightTopImage: '',
        leftBottomImage: '',
        rightBottomImage: '',
        isShowBorder: 1,
        chatBubbleBorder: {
          width: '',
          rounded: '',
          direction: 1,
          gradientColor: []
        },
        chatBubbleText: {
          textFont: '',
          rounded: '',
          direction: 1,
          gradientColor: []
        }
      },
      borderColors: [{ color: '' }],
      contentColors: [{ color: '' }]
    }
  },
  created() {
    this.getList()
    this.handleGetCateData()
  },
  methods: {
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleGetCateData() {
      getCateData().then(res => {
        this.categoryOption = [...this.categoryOption, ...res.data]
        this.addCategoryOption = res.data
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('请上传JPG/PNG格式的图片!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
    },
    handleSpecialFlagBigSuccess() {
      this.editRulesForm.picture = this.ossLastImgUrl
      this.specialFlagBigList = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove() {
      this.specialFlagBigList = []
    },
    handleSpecialFlagBigSuccess2() {
      console.log(this.ossLastImgUrl)
      this.editRulesForm.special = this.ossLastImgUrl
      this.specialFlagBigList2 = [{ url: this.ossLastImgUrl }]
    },
    handleSpecialFlagBigRemove2() {
      this.specialFlagBigList2 = []
    },

    getList() {
      this.listLoading = true
      getData(this.listQuery).then(res => {
        this.tableData = res.data.data
        this.listLoading = false
        this.confirmBtn = false
        this.total = res.data.total
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('editRulesForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      // row)
      this.row_id = row.id
      if (row.category_id === 4) {
        row.special = JSON.parse(row.special).chatBubbleText.gradientColor[0].color
      }
      this.editRulesForm = {
        id: row.id,
        show_type: row.show_type,
        max_wealth: row.max_wealth,
        min_wealth: row.min_wealth,
        cate_id: row.category_id,
        cate_name: row.cate_name,
        product_name: row.product_name,
        special: row.special,
        picture: row.picture,
        style_ids: '1',
        time: row.time
      }
      this.specialFlagBigList = [{ url: row.picture }]
      this.specialFlagBigList2 = [{ url: row.special }]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.editRulesForm = {
          id: undefined,
          grade: undefined,
          experience: undefined,
          head_picture: undefined,
          title: undefined,
          main_icon: undefined,
          basics_icon: undefined,
          style_ids: '1',
          time: undefined
        }
      })

      this.specialFlagBigList = []
      this.specialFlagBigList2 = []
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    submitForm(formName) {
      if (this.confirmBtn) return

      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmBtn = true
          this.editRulesForm.cate_name = undefined
          this.editRulesForm.sale_status = '0'
          this.editRulesForm.days_price = '1:1'
          this.editRulesForm.type = 1
          if (this.editRulesForm.cate_id === 4) {
            this.extraForm.chatBubbleText.gradientColor = [{ color: this.editRulesForm.special }]
            this.editRulesForm.special = JSON.stringify(this.extraForm)
          }
          if (this.dialogStatus == 'create') {
            productAdd(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          } else {

            productEdit(this.editRulesForm).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {
          // 'error submit!!');
          return false
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = row.id.toString()
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {

      if (this.multipleSelection.length === 0) {
        this.$message.warning('请勾选要删除的数据')
        return
      } else {
        let arr = []
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })
        this.dataIds = arr.join(',')
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      // this.dataIds)
      deleteData(this.dataIds).then((response) => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    },
    handleChangeCate(val) {
      console.log(val)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-upload-list__item {
    transition : none !important;
  }

  .el-upload-list--picture {
    max-height : 103px !important;
    overflow   : hidden;
  }
}
</style>
